const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const { put } = require('./ali-oss-upload');

// 申明要上传文件的根目录
const targetDir = path.join(__dirname, '../dist');
// 申明要上传的文件类型
const needUploadExt = ['.js', '.css', '.png', '.jpg', '.jpeg', '.gif'];

/**
 * 扫描指定目录，返回指定类型文件
 * 注意 pathname 是 path.dirname()+path.basename() ，类似 /Users/dist/xxx.js
 * @param {*} dir
 * @param {*} callback 回调里处理扫描到的文件，是文件路径
 */
const scanTargetDir = (dir, callback) => {
  console.log(chalk.blue(`enter dir: ${dir}`));

  const files = fs.readdirSync(dir);
  files.forEach((filename, index) => {
    let pathname = path.join(dir, filename);
    const stats = fs.statSync(pathname);
    if (stats.isDirectory()) {
      // 如果是目录，进入递归
      scanTargetDir(pathname, callback);
    } else if (stats.isFile()) {
      if (needUploadExt.includes(path.extname(pathname))) {
        console.log(chalk.green('get target file:', pathname));
        callback && callback(pathname);
      }
    }
  });

  console.log(chalk.blue(`exit dir: ${dir}`));
};

scanTargetDir(targetDir, (pathname) => {
  put(path.basename(pathname), pathname);
});
